package com.jianying.day07;

import com.jianying.beans.Dept;
import com.jianying.beans.Emp;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.ProcessJoinFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;

/**
 * ClassName: Flink02_Join_intervalJoin
 * Package: com.atguigu.day07
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/4/8 09:38
 * @Version: 1.0
 */
public class Flink02_Join_intervalJoin {
    public static void main(String[] args) throws Exception {
        // TODO intrerval Join 内连接 只支持事件时间
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // TODO 读取员工数据 完成类型转换，指定waterMark
        SingleOutputStreamOperator<Emp> empDS = env
                .socketTextStream("localhost", 8888)
                .map(new MapFunction<String, Emp>() {
                    @Override
                    public Emp map(String s) throws Exception {
                        String[] words = s.split(",");
                        return new Emp(Integer.valueOf(words[0]), words[1], Integer.valueOf(words[2]), Long.valueOf(words[3]));
                    }
                });
        SingleOutputStreamOperator<Emp> empWmDS = empDS.assignTimestampsAndWatermarks(
                WatermarkStrategy
                        // .<Emp>forMonotonousTimestamps()
                        .<Emp>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner(
                                new SerializableTimestampAssigner<Emp>() {
                                    @Override
                                    public long extractTimestamp(Emp emp, long l) {
                                        return emp.getTs()*1000L;
                                    }
                                }
                        )
        );
        empWmDS.print("emp:");

        // TODO 读取部门数据 完成类型转换
        SingleOutputStreamOperator<Dept> deptDS = env
                .socketTextStream("localhost", 8889)
                .map(new MapFunction<String, Dept>() {
                    @Override
                    public Dept map(String s) throws Exception {
                        String[] words = s.split(",");
                        return new Dept(Integer.valueOf(words[0]), words[1], Long.valueOf(words[2]));
                    }
                });
        // TODO 指定waterMark
        SingleOutputStreamOperator<Dept> deptWmDS = deptDS.assignTimestampsAndWatermarks(
                WatermarkStrategy
                        // .<Dept>forMonotonousTimestamps()
                        .<Dept>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner(
                                new SerializableTimestampAssigner<Dept>() {
                                    @Override
                                    public long extractTimestamp(Dept dept, long l) {
                                        return dept.getTs() * 1000L;
                                    }
                                }
                        )
        );
        deptWmDS.print("dept");

        // TODO interval join 关联 只支持事件时间
        // 迟到数据放侧输出流
        OutputTag<Emp> empTag = new OutputTag<Emp>("empLate") {};
        OutputTag<Dept> deptTag = new OutputTag<Dept>("deptLate") {};

        SingleOutputStreamOperator<Tuple2<Emp, Dept>> processDS = empWmDS
                .keyBy(emp -> emp.getDeptNo())
                .intervalJoin(deptWmDS.keyBy(dept -> dept.getDeptNo()))
                .between(Time.milliseconds(-5), Time.milliseconds(5))
                .sideOutputLeftLateData(empTag)
                .sideOutputRightLateData(deptTag)
                .process(
                        new ProcessJoinFunction<Emp, Dept, Tuple2<Emp, Dept>>() {
                            // 关联上会调用这个方法
                            @Override
                            public void processElement(Emp emp, Dept dept, Context ctx, Collector<Tuple2<Emp, Dept>> out) throws Exception {
                                out.collect(Tuple2.of(emp, dept));
                            }
                        }
                );

        processDS.print("join:");
        processDS.getSideOutput(empTag).print("emp迟到数据：");
        processDS.getSideOutput(deptTag).print("dept迟到数据：");

        env.execute();
    }
}
